using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioController
{
    public AudioRoot audioRoot;
    
    public AudioSource bgM;
    public List<AudioSource> effectAudios = new List<AudioSource>();

    private bool bgMState = GameController.Instance().playerDataCtr.setting.BgMState, 
        effectState = GameController.Instance().playerDataCtr.setting.EffectState;
    private int bgMValue = GameController.Instance().playerDataCtr.setting.BgMValue, 
        effectValue = GameController.Instance().playerDataCtr.setting.EffectValue;

    public void SetAllAudio(bool bgMState, bool effectState, int bgMValue, int effectValue)
    {
        if (this.bgMState != bgMState)
        {
            this.bgMState = bgMState;
            SetBGMState(bgMState);
        }

        if (this.effectState != effectState)
        {
            this.effectState = effectState;
            SetEffectAudioState(effectState);
        }

        if (this.bgMValue != bgMValue && bgMState)
        {
            this.bgMValue = bgMValue;
            SetBGMVolume(bgMValue);
        }

        if (this.effectValue != effectValue && effectState)
        {
            this.effectValue = effectValue;
            SetEffectAudioVolume(effectValue);
        }
    }

    private void SetBGMState(bool state)
    {
        if (state)
        {
            bgM.UnPause();
            return;
        }

        bgM.Pause();
    }

    private void SetEffectAudioState(bool state)
    {
        foreach (var effectAudio in effectAudios)
        {
            effectAudio.enabled = state;
        }
    }

    private void SetBGMVolume(int value)
    {
        bgM.volume = (float) value * 0.01f;
    }

    private void SetEffectAudioVolume(int value)
    {
        foreach (var effectAudio in effectAudios)
        {
            effectAudio.volume = (float) value * 0.01f;
        }
    }

    public AudioClip GetMusic(string name)
    {
        if (audioRoot.AudioClipMap[name])
        {
            return audioRoot.AudioClipMap[name];
        }
        Debug.LogError("没有 "+ name + " 音频文件");
        return null;
    }
}